package com.godme.concurrent.util;

import java.util.Random;
import java.util.concurrent.Semaphore;

public class SemaphoreTest {

    private static final Random random = new Random();


    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(3);
        for (int i = 0; i < 5; i++) {
            new MyThread("thread-"+i, semaphore).start();
        }
    }


    static class MyThread extends Thread{

        private final Semaphore semaphore;

        public MyThread(String name, Semaphore semaphore){
            super(name);
            this.semaphore = semaphore;
        }

        @Override
        public void run() {
            while (true){
                try {
                    semaphore.acquire();
                    System.err.println(getName()+" : running");
                    sleep(random.nextInt(2000));
                    semaphore.release();
                    System.err.println(getName()+" : exist");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
